A nested for loop is a loop inside another loop. It allows performing repetitive tasks in a nested or hierarchical manner. The inner loop gets executed completely for each iteration of the outer loop. Nested for loops are useful when dealing with multi-dimensional data structures like matrices or when need to perform tasks that have multiple levels of repetition.
Example of nested for loops to print a pattern of stars in the shape of a triangle.
#include <stdio.h>
int main() {
int rows;
printf("Enter the number of rows for the triangle: ");
scanf("%d", &rows);
for (int i = 1; i <= rows; i++) { // Outer loop to control the rows
for (int j = 1; j <= i; j++) { // Inner loop to control the number of stars in each row
printf("* ");
}
printf("\n"); // Move to the next line after each row is printed
}
return 0;
}
*
* *
* * *
* * * *
* * * * *
The nested for loop efficiently prints the pattern of stars in the shape of a triangle with the specified number of rows. The inner loop prints the stars, and the outer loop controls the number of rows to create the desired pattern.
What is a nested for loop in C used for?
What does the inner loop do in a nested for loop?
What is the primary purpose of using nested for loops in C?